﻿using Basic.FlowApplication.Extend;
using Basic.FlowApplication.Interface;
using Basic.FlowApplication.Model;
using Basic.FlowApplication.Model.AuditLog;
using Basic.FlowExtendService;
using Basic.FlowRemoteModel;
using Basic.FlowRemoteModel.Application.Model;
using Basic.HrRemoteModel.Emp.Model;
using WeDonekRpc.Client.Attr;
using WeDonekRpc.Helper;

namespace Basic.FlowApplication.AuditEvent
{
    /// <summary>
    /// 委托
    /// </summary>
    [IocName("Audit_7")]
    [ClassLifetimeAttr(ClassLifetimeType.SingleInstance)]
    internal class DelegationEvent : IItemAuditEvent
    {
        private readonly IEmpService _Emp;

        public DelegationEvent ( IEmpService emp )
        {
            this._Emp = emp;
        }

        public AfootAuditLogItem ItemAudit ( AuditFlowBody flow, FlowAuditLogState log, AuditRes result )
        {
            AfootAuditLogItem item = log.LogItem.Find(a => a.Id == result.ItemId);
            item.CheckAuditItem(result);

            FlowNode node = flow.Nodes[item.NodeId];
            if ( ( FlowAuditButton.委托 & node.AuditButton ) != FlowAuditButton.委托 )
            {
                throw new ErrorException("flow.audit.not.allow.delegation");
            }
            item.AuditState = FlowAuditItemStatus.已委托;
            item.AuditOpinion = result.Opinion;
            item.SignFileId = result.SignFileId;
            EmpBase emp = this._Emp.GetBase(result.ToEmpId.Value);

            log.LogItem.Add(new AfootAuditLogItem
            {
                CompanyId = emp.CompanyId,
                EmpByDeptId = emp.DeptId,
                EmpByUnitId = emp.UnitId,
                EmpId = emp.EmpId,
                RootBatchNo = item.RootBatchNo,
                RootNodeId = item.RootNodeId,
                NodeId = item.NodeId,
                NodeType = item.NodeType,
                PrevBackNo = item.BatchNo,
                PrevNodeId = item.PrevNodeId,
                PrtBatchNo = item.PrtBatchNo,
                OptItemId = item.Id,
                MarkState = FlowItemMarkState.委托,
                TimeOut = node.LimitTime.HasValue ? DateTime.Now.AddMinutes(node.LimitTime.Value) : null
            });
            return item;
        }
    }
}
